import 'package:flutter/cupertino.dart';


class ListenAppOnActive extends StatefulWidget {
  final  Widget children;


  /// 进入前台
  VoidCallback? onShow;
  /// 进和后台
  VoidCallback? onHide;
  /// 非活动状态
  VoidCallback? onDeActive;
  /// 监听App是否进入后台和前台的widget
  ListenAppOnActive({super.key,required this.children,this.onShow,this.onHide,this.onDeActive});



  @override
  State<ListenAppOnActive> createState() => _ListenAppOnActiveState();
}

class _ListenAppOnActiveState extends State<ListenAppOnActive> with WidgetsBindingObserver {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addObserver(this); // 注册监听

  }

  @override
  void dispose(){
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
      // print("App 进入前台");
      if(widget.onShow != null){
        widget.onShow!();
      }
        break;
      case AppLifecycleState.inactive:
      // print("App 处于非活动状态");
        if(widget.onDeActive != null){
          widget.onDeActive!();
        }
        break;
      case AppLifecycleState.paused:
      // print("App 进入后台");
        if(widget.onHide != null){
          widget.onHide!();
        }
        break;
      case AppLifecycleState.detached:
      // print("App 被销毁");

        break;
      case AppLifecycleState.hidden:
      // TODO: Handle this case.
    }
  }

  @override
  Widget build(BuildContext context) {
    return widget.children;
  }
}
